import memoizeOne from 'memoize-one';
import isEqual from 'lodash/isEqual';
// import { history } from 'umi';
import { getAuthRoutes } from '@/utils/auth/helper';
import { formatter, filterMenuData } from '@/utils/utils';

const memoizeOneFormatter = memoizeOne(formatter, isEqual);

// 格式化权限数据，方便调试
/* eslint no-param-reassign: ["error", { "props": false }] */
// const formatMenuData = data => {
//     if (!data) return;

//     const formatData = {};

//     const typeMap = {
//         1: '目录',
//         2: '菜单',
//         3: '按钮'
//     };

//     const format = (obj, pathAry, item) => {
//         const cate = pathAry.shift();
//         obj[cate] = obj[cate] || {};
//         if (pathAry.length) {
//             format(obj[cate], pathAry, item);
//         } else {
//             const type = typeMap[item.type];
//             if (!type) return;
//             obj[cate][type] = obj[cate][type] || [];
//             obj[cate][type].push({
//                 name: item.menuName,
//                 code: item.code
//             });
//         }
//     };
//     data.forEach(item => {
//         const levels = item.code.split(':');
//         const useLevels = levels[0] === 'office' ? levels.slice(0, 3) : levels.slice(0, 1);
//         format(formatData, useLevels, item);
//     });
// };

const findFirstMenu = menuData => {
    // 一般情况下显示当前路由所在路由树的整个路由
    const rootPath = menuData.find(item => window.location.pathname.includes(item.path));

    // 特殊情况是展示设置了sideRoot属性的路由子集
    let sideRootMenu;
    const checkSideRoot = menu => {
        if (!menu || !window.location.pathname.includes(menu.path) || sideRootMenu) {
            return;
        }

        if (menu.sideRoot) {
            sideRootMenu = menu;
            return;
        }

        if (menu.children) menu.children.forEach(item => checkSideRoot(item));
    };
    checkSideRoot(rootPath);

    return window.location.pathname === '/' ? menuData[0] : sideRootMenu || rootPath;
};

export const updateMenu = (data, path, obj) =>
    data.map(item => {
        if (item.path === path) {
            return {
                ...item,
                ...obj
            };
        }
        if (item.children) {
            return {
                ...item,
                children: updateMenu(item.children, path, obj)
            };
        }
        return item;
    });

const setNewName = (data, path, newName) => {
    if (data) {
        return data.map(item => {
            if (item.path === path && item.nameChangeable) {
                return {
                    ...item,
                    name: newName
                };
            }
            if (item.children) {
                return {
                    ...item,
                    children: setNewName(item.children, path, newName)
                };
            }
            return item;
        });
    }
    return data;
};

export default {
    namespace: 'menu',

    state: {
        originalMenuData: [],
        firstMenu: {}, // 保存第一层菜单
        menuData: [], // 保存第二层一下的菜单
        breadcrumbNameMap: {},
        result: [],
        filterRoutes: [],
        authData: []
    },

    effects: {
        *getMenuData({ payload, callback }, { call, put }) {
            const { routes, authority, path } = payload;
            // const { pathname } = window.location;

            const { tmpRoutes, filterRoutes, flatterMenu } = yield call(getAuthRoutes, routes);

            // formatMenuData(filterRoutes);

            const menuData = filterMenuData(memoizeOneFormatter(tmpRoutes, authority));
            const originalMenuData = memoizeOneFormatter(tmpRoutes, authority, path);
            const breadcrumbNameMap = flatterMenu;

            yield put({
                type: 'save',
                payload: {
                    originalMenuData,
                    menuData,
                    breadcrumbNameMap,
                    authData: filterRoutes,
                    firstMenu: findFirstMenu(menuData),
                    routerData: routes
                }
            });
            if (callback) {
                callback(breadcrumbNameMap);
            }
        }
    },

    reducers: {
        save(state, action) {
            return {
                ...state,
                ...action.payload
            };
        },
        saveMenu(state, { payload }) {
            const { count, path } = payload;

            const tmpMenuData = updateMenu(state.menuData, path, {
                count
            });
            return {
                ...state,
                menuData: tmpMenuData
            };
        },
        // 流程表单动态修改标签名称
        changeMenuName(state, { payload }) {
            const { path, newName } = payload;
            const { originalMenuData } = state;
            return {
                ...state,
                originalMenuData: setNewName([...originalMenuData], path, newName)
            };
        },
        // 动态修改标签名称
        updateTabTitle(state, { payload }) {
            const { pathname, title } = payload;
            const { breadcrumbNameMap } = state;
            const final = { ...breadcrumbNameMap };
            if (final[pathname]) {
                final[pathname].name = title;
            }
            return {
                ...state,
                breadcrumbNameMap: final
            };
        }
    }
};
